﻿/*
 *  messagelist.js
 *  scrollable message list with memory of recent operations.
 */
(function ($) {
    $.widget('hqpad.messagelist', {

        options: {
            messageDuration: 6000
        },

        vars: {
            queue: null,
            //history: null,
            open: false,
            listContainer: null,
            box: null
        },

        _create: function () {
            // start by hiding the message list area.
            this.element.hide();

            // create outer box.
            var box = $('<div></div>');
            box.addClass('message-list');
            this.element.append(box);

            // create container ul.
            var ul = $('<ul></ul>');
            box.append(ul);

            // create default private vars.
            this.vars = {
                queue: new Array(),
                //history: new Array(),
                open: false,
                listContainer: ul,
                box: box
            };

        },

        /*
        *  start processing items.
        */
        _process: function () {
            var plugin = this;

            // check the message queue and get next item.
            if (!this.vars.queue || this.vars.queue.length == 0) {
                // if visible timeout the display.
                plugin._hideBox();
                return;
            }

            var next = this.vars.queue.pop();

            // display the message.
            var li = $('<li></li>');
            li.addClass(next.type);
            li.html(next.message);
            plugin.vars.listContainer.prepend(li);

            // show the messagebox.
            if (!plugin.vars.open) {
                plugin.element.fadeIn(200);
                plugin.vars.open = true; // flag that we are processing.
            }

            // if there are no more messages to display hide box.
            if (!plugin.vars.queue || this.vars.queue.length == 0)
                plugin._hideBox();
            else {
                // display the next item after a throttle pause.
                setTimeout(function () {
                    plugin._process();
                }, 200);
            }
        },

        _hideBox: function () {
            var plugin = this;

            setTimeout(function () {
                plugin.element.fadeOut(300);
                plugin.vars.open = false;
            }, plugin.options.messageDuration);
        },

        /*
        *  public function.
        *  push a new message queue item onto the list.
        *  message: the text message to display.
        *  type: error, warning or info.
        */
        push: function (message, type) {

            this.vars.queue.push({ message: message, type: type });

            if (!this.vars.active)
                this._process(); // start processing
        }

    });
})(jQuery);